/**
 * @author killer-g
 * @version 0.2 alpha
 * @projectDescription
 * 
 * Not working jQuery selectors:
 * remove
 * slideDown Slow with hidden elementes -> display:none;
 */
var file = null;

var edit_file = null;
/**
 * the array holding the current handled files [0]=> windows/file/path/.exe
 */
var files_db =[];

/**
 * debug flag
 */
var debug_on = true;

/**
 * initial on load .. must be replaced with jQuerys version
 */
function doLoad()
{
	
	air.trace('hello im in');
	
	$('#container').tabs();
	if(debug_on == true)
	{
		$('#debug').css('display','block');
		$('#debug').append('<h4>Debug Output');
		
	}
	file = air.File.documentsDirectory;
	file.addEventListener( air.Event.SELECT, doSelect );	
	
	edit_file = air.File.documentsDirectory;
	edit_file.addEventListener( air.Event.SELECT, doReadFile );	
	//add browse button search for an existing batch file	
	document.getElementById( "btnBrowseExisting" ).addEventListener( "click", doBrowseEdit );

	
	
	//add browse button event
	document.getElementById( "btnBrowse" ).addEventListener( "click", doBrowse );
	//add save button even
	document.getElementById( "btnSave" ).addEventListener( "click", writeBatchFile );
	//add drag enter event
	window.htmlControl.addEventListener(air.DragEventENTER, doEnter ); // runtime.flash.events.NativeDragEvent.NATIVE_DRAG_ENTER
	//dragging out of range
	window.htmlControl.addEventListener( air.DragEventEXIT, doDragExit );
	//add drag drop event
	window.htmlControl.addEventListener( runtime.flash.events.NativeDragEvent.NATIVE_DRAG_DROP, doDrop );
//	var mem = window.runtime.flash.system.System.totalMemory;
//	console.log('Memmory:' + mem);
}
/**
 * open the the native filedialog
 */
function doBrowse()
{
	var filters = new window.runtime.Array();
	
	filters.push( new air.FileFilter( "Windows Executables", "*.exe" ) );
	file.browseForOpen( "Select a Window Programm Start File", filters );
}	
/**
 * after a file is selected in the native filedialog
 */
function doSelect()
{
	//push onto local js array db
	files_db.push(file.nativePath);
	//appen li
	$('#filelist ul').append('<li>' + file.nativePath +'</li>');			
}
/**
 * when a file is dragged over the air window
 */
function doEnter(e)
{
	if( e.transferable.hasFormat( air.TransferableFormats.FILE_LIST_FORMAT ) )
	{
		air.DragManager.acceptDragDrop( window.htmlControl );
		
		$('#filelist ul').append('<li class="empty">File in the Hole ... Incoming </li>');
		$('li.empty').slideDown('slow');
		$('li.empty').css('visibility','visible');		
	}
	
}
/**
 * when a formerly dragged over file is dragged away for the air window
 */
function doDragExit(e)
{
	$('#filelist ul li.empty').slideUp();
	$('#filelist ul li.empty').remove();
}


/**
 * when a file is dropped in the air window
 */
function doDrop(e)
{	
	var files = e.transferable.dataForFormat( air.TransferableFormats.FILE_LIST_FORMAT, air.TransferableTransferMode.ORIGINAL_PREFERRED );
 	var file;
	var file_list = '';
	
	//remove drop box
	$('#filelist ul li.empty').slideUp();
	$('#filelist ul li.empty').remove();
		
	for( var i = 0; i < files.length; i++ )
	{
		files_db.push(files[i].nativePath);
		//$('#filelist ul').append('<li>' + files[i].nativePath +'</li>');	
	}	
	
	for( var i = 0; i < files_db.length; i++ )
	{		
		//$('#filelist ul').append();
		file_list += '<li id="list_' + i + '">' + files_db[i] +'<span class="delete">delete</span</li>';
	}		
	$('#filelist ul').append(file_list);	
}
/**
 * remove a file from the db array and remove the li
 */
function removeFromList()
{
	
	//files_db =[];
}
/**
 * Writes all selected filenames
 */
function writeBatchFile()
{
	// the filename
	var batch_filename = $('#fileName').attr("value");
	// the file
	var file = air.File.desktopDirectory.resolve( batch_filename + ".bat" );
	//the streaming old pipe
	var stream = new air.FileStream();
	
	//start content
	var content = '@echo off\n';
	
	for (var i=0;i<files_db.length;i++)
	{//loop over filelist
		 content +='Start "ProgrammName" /MIN ' +'"'+ files_db[i] + '"\n';
	}
	//append clearscreen command .. might work without
	content += 'cls';
	stream.open( file, air.FileMode.WRITE );	
	stream.writeMultiByte(content, air.File.systemCharset );
	stream.close();	
}

function doBrowseEdit()
{
	var filters = new window.runtime.Array();	
	filters.push( new air.FileFilter( "Windows Executables", "*.bat" ) );
	edit_file.browseForOpen( "Select a Batch File", filters );	
}

function doReadFile()
{
	//debug(edit_file.nativePath);
	stream = new air.FileStream();
	
	stream.addEventListener( air.ProgressEvent.PROGRESS, doReadComplete );
	
	stream.openAsync( edit_file, air.FileMode.READ );
	
}
function doReadComplete(event)
{
	var data = stream.readMultiByte( stream.bytesAvailable, air.File.systemCharset );

//	var regex = new RegExp("\\n");
//	var out = data.replace('<br>', regex)
	var programms =[];
	var start_line = 1;//only start at second element of array	
	var lines = [];

	lines = data.split(/(\r\n|\r|\n)/g);
	
	
	for (var i=0;i<lines.length;i++)
	{//loop over filelist
		 if(i >= start_line)
		 {//only start at second element of array
		 	//split again  into pieces of
			 	//	add to programms array -> filepath, /min, name, ...
				//var properties = lines[i].split(/\w+\s/g);
			//programms.push(properties);
			//debug(lines[i]);
		 }
		 
		 
	}
	debug(programms);
	debug(lines[0]);
	
	if( event.bytesLoaded == event.bytesTotal )
	{
		stream.close();
	}
	
}

function debug(data){
	
/*	if(typeof data == 'object')
	{
		data += 'ein objekt: ';
	}
	$('#debug').append(typeof data);
*/
	if(debug_on == true)
	{
		$('#debug').append(data);
	}
}